<?php

namespace App\Observers;

use App\Models\Child;
use App\Models\Device;
use App\Models\Family;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Matrix\Exception;

class ChildObserver
{
    /**
     * 监听 Child 创建事件。
     *
     * @param  \App\Models\Child  $child
     * @return void
     */
    //public function forceDeleted(Child $child)
    public function deleted(Child $child)
    {
        if (!$child->isForceDeleting()){
            Log::error("not forceDelete");
            return;
        }

        DB::beginTransaction();
        try {

            if ($child->childStars()->exists() && !$child->childStars()->delete()) {
                throw new \Exception("childStars delete false");
            }
            if ($child->currentChildren()->exists() && !$child->currentChildren()->delete()) {
                throw new \Exception("currentChildren delete false");
            }

            if ($child->where("phone", $child->phone)->count() == 1 && !Family::where("phone", $child->phone)->delete()) {
                throw new \Exception("Family delete false");
            }

            if ($child->histories()->exists() && !$child->histories()->delete()) {
                throw new \Exception("histories delete false");
            }

            if ($child->assessments()->exists() && !$child->assessments()->delete()) {
                throw new \Exception("histories delete false");
            }

            Log::error("child about is delete");
            DB::commit();
        } catch (Exception $exception) {
            Log::error("child delete fail." . $exception);
            DB::rollBack();
        }

    }
}
